package net.minhdiep.androiddialoglistener.util;
/*
 * User: Minh Diep
 * Date: 5/19/13
 * Time: 12:06 AM
 */

import android.content.Intent;
import android.os.AsyncTask;
import android.support.v4.content.LocalBroadcastManager;
import net.minhdiep.androiddialoglistener.components.SubBroadcastReceiver;
import org.xmlpull.v1.XmlPullParserException;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.SocketTimeoutException;
import java.net.URL;

public class DownloadXmlBR extends AsyncTask<String, Integer, String> {

    private LocalBroadcastManager localBroadcastManager;

    public DownloadXmlBR(LocalBroadcastManager localBroadcastManager){
        this.localBroadcastManager = localBroadcastManager;
    }

    @Override
    protected String doInBackground(String... strings) {
        try {
            return downloadUrl(strings[0]);
        } catch (XmlPullParserException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);
        Intent broadcastIntent = new Intent(SubBroadcastReceiver.INTENT_FILTER_NAME);
        broadcastIntent.putExtra(SubBroadcastReceiver.DATA_RECEIVE_STR, s);
        broadcastIntent.setAction(SubBroadcastReceiver.DATA_RECEIVE_ACTION);
        localBroadcastManager.sendBroadcast(broadcastIntent);
    }

    private String convertStreamToString(InputStream is) {
        java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
        return s.hasNext() ? s.next() : "";
    }

    private String downloadUrl(String string) throws IOException, XmlPullParserException {
        InputStream is = null;
        try {
            URL url = new URL(string);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(10000 /* milliseconds */);
            conn.setConnectTimeout(10000 /* milliseconds */);
            conn.setRequestMethod("GET");
            conn.connect();
            int response = conn.getResponseCode();
            if (response == 200) {
                is = conn.getInputStream();
                return convertStreamToString(is);
            } else
                return null;
        } catch (SocketTimeoutException e) {
            return null;
        } finally {
            if (is != null) {
                is.close();
            }
        }
    }
}
